package server;

import com.lagou.http.HttpServlet;
import com.lagou.http.Request;
import com.lagou.http.Response;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

/**
 * @author stevejson
 * 请求处理线程
 */
public class RequestProcessor extends Thread {

    private Socket socket;
    private Mapper wrapperMapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.wrapperMapper = mapper;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName());
            InputStream inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            String[] split = request.getUrl().split("/");
            String part1;
            String part2;
            if(split.length < 2 ){
                response.outPutHtml(request.getUrl());
            }
            if (split.length == 2 ) {
                part1 = "/" + split[0];
                part2 = "/" + split[1];
            } else {
                part1 = "/" + split[1];
                part2 = "/" + split[2];
            }
            //获取servletMap   获取servlet  处理请求
            Map<String, HttpServlet> servletMap = wrapperMapper.getServletMap(part1);
            if (servletMap == null || servletMap.get(part2) == null) {
                response.outPutHtml(request.getUrl());
            } else {
                HttpServlet httpServlet = servletMap.get(part2);
                httpServlet.service(request, response);
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
